#!/usr/bin/env ruby

require 'zlib'

RedBook::Parser.operations = [:archive, :restore, :blank, :backup]

class RedBook::Logger
	
	# Initialize archiver hooks. <i>[Archiver Plugin]</i>
	def initialize_archiver
	
		@hooks.add :sort_config_header do |args|
			args[:scfg][:archive] = {:info => 'Archiving Settings'}
			false
		end
		
		@hooks.add :sort_config_match do |args|
			if args[:index].to_s =~ /backups_folder|archives_folder/ && args[:scfg][:archive] then
				args[:scfg][:archive] << { args[:index] => args[:value], :_attributes => {:raw => true}}
				true
			end
		end
	end
	
	# Delete the current log file. <i>[Archiver Plugin]</i>
	#
	# <i>Message Format:</i> n/a
	def blank
		if (user_confirmation("Do you really want to delete the contents of your #{@alias} log file?")) then
			@log = []
			File.open(get_log_path(@alias), 'w+') do |f|
				f.puts ''
			end
			notify({:info => "#{@alias.capitalize} log contents deleted."})
		else
			notify({:info => "Operation cancelled."})
		end
	end
	
	# Backup the current log to another YAML file in the same directory 
	# (name: <log-name>.bkp.yml). <i>[Archiver Plugin]</i>
	#
	# <i>Message Format:</i> n/a
	def backup
			# Set file name and type
			suffix = File.extname(@@config[:data])
			log_file = File.basename(@@config[:data], suffix)
			backup_file = @@config[:data].gsub(suffix, '')+'.bkp'+suffix
			begin
				notify({:info => "Log backup in progress..."})
				old_dataset = @dataset
				# Execute a silent :select to load all messages into the dataset
				process ":select :silent"
				# Execute a :save to save the backup
				process ":dataset #{backup_file} :silent"
				move_file(backup_file, @@config[:backups_folder], "backups") unless !@@config[:backups_folder] || @@config[:backups_folder] == ""
				@command[:silent] = false
				@dataset = old_dataset
				notify({:success => "Log successfully backed up."})
			rescue
				raise LoggerError, 'Unable to backup log file.'
			end
	end
	
	# Restore the backup of the current log file. <i>[Archiver Plugin]</i>
	#
	# <i>Message Format:</i> n/a
	def restore
		if (user_confirmation("Do you really want to restore the backup of your #{@alias} log file?")) then
			backup_file = File.basename(get_log_path(@alias).gsub(/yml$/, 'bkp.yml').gsub(/\\/, "/"))
			if File.exist?(@@config[:backups_folder]+"/"+backup_file) then
				@@config[:data] = @@config[:backups_folder]+"/"+backup_file
				@command[:message] = ''
				@command[:silent] = true
				refresh
				@@config[:data] = get_log_path(@alias)
				overwrite_log
				notify({:info => "#{@alias.capitalize} log backup restored."})
			else
				notify({:warning => "Backup file not found, operation aborted."})
			end
		else
			notify({:info => "Operation cancelled."})
		end
		
	end

	# Archive (gz) the current log file. <i>[Archiver Plugin]</i>
	#
	# <i>Message Format:</i> n/a
	def archive
		process ":refresh :silent"
		old_dataset = @dataset
		reset
		notify({:info => "Archiving #{@alias} log file..."})
		archive_file = @@config[:data].gsub(/\.(yaml|yml)$/, '')+"_#{Time.now.strftime("%Y-%m-%d@%H.%M.%S")}.yml"+'.gz'
		Zlib::GzipWriter.open(archive_file) do |gz|
			@log.each do |a|
				gz.write a.to_yaml
			end
		end
		move_file(archive_file, @@config[:archives_folder], "archives") unless !@@config[:archives_folder] || @@config[:archives_folder] == ""
		@dataset = old_dataset
		notify({:success => "Done."})
	end

end
